from flask import Flask,request,jsonify
from mongoengine import *
import json

connect('sbo',username='kobako', password='qwer1234', authentication_source='admin')

class User(Document):
  name = StringField(required=True)
  pwd = StringField(required=True)
  nick = StringField(required=True) 
  def __str__(self):
      return "name:%s nick:%s pass:%s" % (self.name,self.nick,self.pwd)

class Player(Document):
    username = StringField(required=True)
    power = IntField(required=True)
    level = IntField(required=True)
    name = StringField(required=True)
    growth_factor = IntField(required=True)
    exp = IntField(required=True)

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, World!'

@app.route('/login',methods=['POST'])
def login():
    name = request.form['name']
    pwd = request.form['pass']
    return jsonify(ok=True) if is_user_exist(name,pwd) else jsonify(ok=False)

@app.route('/player/<username>')
def player(username):
    print username
    p = Player.objects(username=username).first()
    return jsonify(power=p.power,level=p.level,name=p.name,growth_factor=p.growth_factor,exp=p.exp)


def is_user_exist(name,pwd):
    it = User.objects(Q(name=name) & Q(pwd=pwd)).first()
    return True if it is not None else False


app.run(debug=True)